package com.cmw.auntapp.ui;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.cmw.auntapp.R;
import com.cmw.auntapp.component.ArrivalTimeDialog;
import com.cmw.auntapp.component.OrderCancelDialog;
import com.cmw.auntapp.constant.CommandType;
import com.cmw.auntapp.constant.Constant;
import com.cmw.auntapp.core.base.vo.DataResult;
import com.cmw.auntapp.core.util.DateUtil;
import com.cmw.auntapp.core.util.FormUtil;
import com.cmw.auntapp.core.util.SharedPreferencesUtil;
import com.cmw.auntapp.core.util.StringHandler;
import com.cmw.auntapp.core.util.ToastAlert;
import com.cmw.auntapp.model.LocationModel;
import com.cmw.auntapp.presenter.OrderPresenter;
import com.cmw.auntapp.service.LocationService;
import com.cretin.www.externalmaputilslibrary.OpenExternalMapAppUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.cmw.auntapp.R2.id.tv_address_val;
import static com.cmw.auntapp.R2.id.tv_cname_val;
import static com.cmw.auntapp.R2.id.tv_code_val;
import static com.cmw.auntapp.R2.id.tv_tel_val;
import static com.cmw.auntapp.constant.Constant.AUNT_LOCATION_KEY;
import static com.cmw.auntapp.constant.Constant.ORDER_XSTATUS_SERVICE_IN;
import static com.cmw.auntapp.core.util.ToastAlert.ACTIONBTN_OK;


/**
 * 接单详情
 * @Auth chengmingwei
 * @date 2021-04-19 20:37
 */
public class OrderReceiveActivity extends BaseActivity {

    @BindView(R.id.tv_grabbing_orders)
    TextView tvGrabbingOrders;

    @BindView(R.id.vw_defaultStatus)
    View vwDefaultStatus;

    @BindView(R.id.tv_arrival_time)
    TextView tvArrivalTime;

    ArrivalTimeDialog timeDialog;

    OrderCancelDialog.Builder dialogBuilder = null;

    private OrderPresenter orderPresenter;

    private JSONObject orderData; //订单数据

    private String selectMinutes;   // 当前选择的到达时间

    @Override
    protected int getActivityLayout() {
        return R.layout.activity_order_receive;
    }

    @Override
    void onInit(Bundle savedInstanceState) {
        setTitle(R.string.order_detail_title);
        AssetManager assets = getAssets();
        Typeface fromAsset = Typeface.createFromAsset(assets, "fonts/dfbudingw12_gb.ttf");
        tvGrabbingOrders.setTypeface(fromAsset);
        this.timeDialog = new ArrivalTimeDialog(this, view -> setArrivalTime(view));
        orderPresenter = new OrderPresenter(this);
        checkPermissionRequest();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG, "onResume...");
        loadData();
    }

    private void loadData() {
        String orderId = getOrderId();
        orderPresenter.get(orderId);
    }

    private String getOrderId() {
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        return bundle.getString("orderId");
    }

    public void checkPermissionRequest() {
        RxPermissions permissions = new RxPermissions(this);
        permissions.setLogging(true);
        permissions.request(Manifest.permission.CALL_PHONE).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                Log.e(TAG, "找打电话权限申请："+(aBoolean ? "成功" : "失败"));
            }
        });
    }

    /**
     * 地址导航
     * see: https://github.com/MZCretin/ExternalMapUtils 导航使用说明(须安装高德或百度)
     * @param view
     */
    @OnClick(R.id.btn_navigation_map)
    public void doNavigation(View view) {
        Log.w(TAG,"doNavigation . 地址导航...");
        if (!checkDataReady()) {
            return;
        }
        SharedPreferencesUtil util = SharedPreferencesUtil.getInstance(this);
        LocationModel locationModel = util.getObject(AUNT_LOCATION_KEY, LocationModel.class);
        String anchor = locationModel.getAnchor();
        String sourceLongitude = locationModel.getLongitude().toString();
        String sourceLatitude = locationModel.getLatitude().toString();
        //B.longitude,B.latitude
        String longitude = orderData.getString("longitude");
        String latitude = orderData.getString("latitude");
        String address = orderData.getString("address");
        String appName = getResources().getString(R.string.app_name);

        //
        OpenExternalMapAppUtils.openMapDirection(this, sourceLongitude, sourceLatitude, anchor,
                longitude, latitude, address, appName);

        //打开app端导航 使用高德和百度
        OpenExternalMapAppUtils.openMapNavi(this, longitude, latitude, address, address, appName);
    }

    /**
     * 打电话
     * @param view
     */
    @OnClick(R.id.btn_call_tel)
    public void doCallTel(View view) {
        Log.w(TAG,"doCallTel . 打电话...");
        if (!checkDataReady()) {
            return;
        }
        String phoneNum = orderData.getString("compnayTel");
        phoneNum = phoneNum.replace("-", "");
        Intent intent = new Intent(Intent.ACTION_CALL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        startActivity(intent);
    }

    private boolean checkDataReady() {
        if (null == orderData || orderData.isEmpty()) {
            ToastAlert.showMsg("数据环境还未准备好，请稍后再重新尝试打开当前页面！");
            return false;
        }
        return true;
    }

    /**
     * 到达时间
     * @param view
     */
    @OnClick(R.id.btn_arrival_time)
    public void showArrivalTime(View view) {
        Log.w(TAG,"setArrivalTime . 到达时间...");
       // ArrivalTimeDialog bottomSheetDialog = new ArrivalTimeDialog(this);
        timeDialog.show();
    }

    /**
     * 更新到达时间
     * @param confirmBtn
     * @return
     */
    private boolean setArrivalTime(View confirmBtn) {
        int minutes = timeDialog.getValue();
        if (minutes == 0) {
            ToastAlert.showMsg("请选择到达时间!");
            return false;
        }
        selectMinutes = minutes+"";
        String orderId = getOrderId();
        orderPresenter.setArriveTime(orderId, selectMinutes);
        return true;
    }

    /**
     * 取消订单
     * @param view
     */
    @OnClick(R.id.btn_cancel_order)
    public void cancelOrder(View view) {
        Log.w(TAG,"cancelOrder . 取消订单...");
        if (!checkDataReady()) {
            return;
        }
        Date receiveTime = orderData.getDate("receiveTime");
        Date expireDate = DateUtil.addHourAndMinute(receiveTime,0, 5);
        Date currDateTime = new Date();
        if (DateUtil.compareDate(expireDate, currDateTime) < 0) {
            showOrderCancelDialog();
        } else {
            ToastAlert.confirm(this,"是否确认取消此订单？", (btnText) -> {
                if (!ACTIONBTN_OK.equals(btnText)) {
                    return;
                }
                doCancelOrder("5分钟内取消，原因：无");
            });
        }
    }

    private void showOrderCancelDialog() {
        if (dialogBuilder == null) {
            dialogBuilder = new OrderCancelDialog.Builder(this);
            dialogBuilder.setTitle("取消提示");
            dialogBuilder.setPositiveButton("不取消", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    //设置你的操作事项
                    // Toast.makeText(OrderReceiveActivity.this,"queding",Toast.LENGTH_SHORT).show();
                }
            });

            dialogBuilder.setNegativeButton("确认取消",
                    new android.content.DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            String cancelReason = dialogBuilder.getValue();
                            if (TextUtils.isEmpty(cancelReason)) {
                                ToastAlert.showMsg("请输入取消原因!");
                                return;
                            }
                            doCancelOrder(cancelReason);
                            dialog.dismiss();

                        }
                    });
        }
        dialogBuilder.create().show();
    }

    /**
     * 执行取消订单业务
     * @param cancelReason
     */
    private void doCancelOrder(String cancelReason) {
        String orderId = getOrderId();
        orderPresenter.cancel(orderId, cancelReason);
    }



    /**
     * 上钟
     * @param view
     */
    @OnClick(R.id.btn_on_work)
    public void doOnWork(View view) {
        Log.w(TAG,"doOnWork . 上钟...");
        String orderId = getOrderId();
        ToastAlert.confirm(this, "上钟提醒", "您确定要开始上钟吗？", (actionBtn)->{
            if (actionBtn.equals(ToastAlert.ACTIONBTN_CANCEL)) {
                return;
            }
            orderPresenter.updateXstatus(orderId, ORDER_XSTATUS_SERVICE_IN+"");
        });
    }

    /**
     * 我的 -> 跳转到用户中心
     */
    @OnClick(R.id.iv_my_center)
    public void doGoUserCenter(View view){
        boolean isLogin = orderPresenter.isLogin();
        if (!isLogin) {
            go(LoginActivity.class);
            return;
        }
        Constant.userCenterBackActivity = this.getClass();
        go(UserCenterActivity.class);
    }

    @Override
    protected boolean doFailure(CommandType commandType, DataResult dataResult) {
        switch (commandType) {
            case GET:{ //订单详情数据

                break;
            } case PUT:{ // 在/离岗切换失败
                break;
            }
        }
        return true;
    }

    @Override
    protected boolean doSuccess(CommandType commandType, DataResult dataResult) {
        switch (commandType) {
            case GET:{ //订单详情数据
                orderData = (JSONObject)dataResult.getDatas();
                setValues();
                break;
            } case SET_ARRIVETIME:{ // 到达时间设置成功
                restartCountDown();
                break;
            } case SAVE:{ // 取消订单
                Map<String, String> params = new HashMap<>();
                params.put("orderId", getOrderId());
                go(OrderDetailActivity.class, params); //跳转到订单详情页面
                break;
            }case PUT:{ // 上钟成功后回调
                Map<String, String> params = new HashMap<>();
                params.put("orderId", getOrderId());
                go(OrderServiceActivity.class, params); //跳转到订单服务中页面
                break;
            }
        }
        return true;
    }

    /**
     * 设置到过时间后重新计时
     */
    private void restartCountDown() {
        String estimateTimeStr = getResources().getString(R.string.order_detail_tip_estimate_time);
        String arrivalTimeStr = String.format(estimateTimeStr, selectMinutes);
        tvArrivalTime.setText(arrivalTimeStr);
        orderData.put("arriveLong", selectMinutes);

        Log.e(TAG, "重新计时功能暂未实现");
    }

    /**
     * 为页面元素赋值
     */
    private void setValues() {
        int[] viewIds = new int[]{tv_code_val,tv_cname_val,tv_address_val,tv_tel_val};
        FormUtil.setValues(this, orderData, viewIds);
        this.selectMinutes = orderData.getString("arriveLong");
        restartCountDown();
    }
}